package core.dispatch.event.player;

import BaseCommon.CommLog;
import cenum.DispatcherComponentEnum;
import com.ddm.server.common.CommLogD;
import com.ddm.server.common.Config;
import com.ddm.server.dispatcher.executor.BaseExecutor;
import com.ddm.server.http.client.HttpAsyncClient;
import com.ddm.server.http.client.IResponseHandler;
import com.google.gson.JsonObject;
import lombok.Data;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;

@Data
public class PlayerIDCardEvent implements BaseExecutor{
    private long pid;
    private int startTime;
    private int endTime;


    public PlayerIDCardEvent(long pid, int startTime, int endTime) {
        this.setPid(pid);
        this.setStartTime(startTime);
        this.setEndTime(endTime);
    }

    @Override
    public void invoke() {
        if (Config.DE_DEBUG()){
            // 测试模式下无需请求
            return;
        }
        // 请求账号服地址
        String url = System.getProperty("PlayerIDCardURL");
        StringEntity stringEntity = null;
        try {
            JsonObject json = new JsonObject();
            json.addProperty("pid", this.getPid());
            json.addProperty("startTime", this.getStartTime());
            json.addProperty("endTime", this.getEndTime());
            json.addProperty("ServerID", 5001);
            stringEntity = new StringEntity(json.toString(), "UTF-8");
            stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        } catch (Exception e) {
            CommLogD.error("请求[{}]封装post参数失败:{}", url, e.toString());
        }
        if (stringEntity == null || url==null) {
            return;
        }
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
        httpPost.setEntity(stringEntity);
        // 通知系统
        HttpAsyncClient.startHttpPost(httpPost, new IResponseHandler() {

            @Override
            public void compeleted(String response) {
                CommLog.info("PlayerIDCardEvent response:{}",response );
            }

            @Override
            public void failed(Exception exception) {
                String url = System.getProperty("PlayerIDCardURL");
                CommLogD.error("PlayerIDCardEvent url:{} 通知回包失败：{}", url, exception.toString());
            }
        });
    }


    @Override
    public int threadId() {
        return DispatcherComponentEnum.ID_CARD.id();
    }

    @Override
    public int bufferSize() {
        return DispatcherComponentEnum.ID_CARD.bufferSize();
    }
}
